package com.winit.menu.web;

import com.winit.common.base.BaseController;
import com.winit.common.base.ExecuteResult;
import com.winit.menu.model.MatrixMenu;
import com.winit.menu.service.MatrixMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by wangjian on 2017/10/27.
 */
@RestController
@Api(value = "menu", tags = {"menu"}, description = "menu")
@RequestMapping(value = "/api/v1/menu")
public class MenuController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(MenuController.class);

    @Autowired
    MatrixMenuService matrixMenuService;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "保存menu tree ")
    @CacheEvict(cacheNames = {"tree_menu", "feature_base_tree"}, allEntries = true)
    public
    @ResponseBody
    Map save(@RequestBody MatrixMenu menu) {
        if (null == menu) {
            logger.error("com.winit.menu.web.MenuController.save no params got....");
            return this.getRtn(BaseController.REQUEST_ERROR, "no params got", null);
        }
        Assert.hasText(menu.getStatus(), "保存menu，status不能为空");
//        Assert.hasText(menu.getReq_id(), "保存menu，req id不能为空");

        try {
            MatrixMenu m = matrixMenuService.saveMenu(menu);
//            menuService.applyMenuUpdate(null, null,m.getSys());
            return getRtn(BaseController.REQUEST_SUCCESS, BaseController.REQUEST_SUCCESS_MSG,m);
        } catch (Exception e) {
            logger.error("com.winit.menu.web.MenuController.save 异常", e);
            return getRtn(BaseController.REQUEST_ERROR, e.getMessage());
        }
    }


    @RequestMapping(value = "/createRootMenu", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "创建menu根节点 ")
    @CacheEvict(cacheNames = {"tree_menu", "feature_base_tree"}, allEntries = true)
    public
    @ResponseBody
    Map createRootMenu(@ApiParam(value = "sys", required = true) @RequestParam(value = "sys", required = true) String sys) {
        if (StringUtils.isEmpty(sys)) {
            logger.error("com.winit.menu.web.MenuController.createRootMenu no params got....");
            return this.getRtn(BaseController.REQUEST_ERROR, "no params got", null);
        }

//        Assert.hasText(menu.getReq_id(), "保存menu，req id不能为空");

        ExecuteResult executeResult = this.matrixMenuService.createRootMenu(sys);
        return this.getRtn(executeResult.getCode(), executeResult.getMsg(), executeResult.getData());
    }

    /**
     * 这个接口目前用于清理数据
     * @param menuId
     * @return
     */
    @RequestMapping(value = "/deleteMenu", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "删除menu，这个接口目前用于清理数据")
    @CacheEvict(cacheNames = {"tree_menu", "feature_base_tree"}, allEntries = true)
    public
    @ResponseBody
    Map deleteMenu(@ApiParam(value = "deletePageFeature, 是否删除其下的所有feature,0-否，1-是,缺省为0", required = false) @RequestParam(value = "deletePageFeature", defaultValue = "0") String deletePageFeature,
                   @ApiParam(value = "menuId", required = true) @RequestParam(value = "menuId", required = true) String menuId) {
        if (null == menuId) {
            logger.error("com.winit.menu.web.MenuController.deleteMenu, menuId不能为空....");
            return this.getRtn(BaseController.REQUEST_ERROR, "menuId不能为空....", null);
        }
        boolean deleteAllPageFeature = "1".equals(deletePageFeature) ? true : false;
        try {
            MatrixMenu m = matrixMenuService.deleteMenuById(menuId, deleteAllPageFeature);
//            menuService.applyMenuUpdate(null, null,m.getSys());
            return getRtn(BaseController.REQUEST_SUCCESS, BaseController.REQUEST_SUCCESS_MSG,m);
        } catch (Exception e) {
            logger.error("com.winit.menu.web.MenuController.deleteMenu 异常", e);
            return getRtn(BaseController.REQUEST_ERROR, e.getMessage());
        }
    }

//    @RequestMapping(value = "/init", method = RequestMethod.POST)
//    @ResponseStatus(HttpStatus.OK)
//    @ApiOperation(value = "初始化导入menu")
//    public
//    @ResponseBody
//    Map initMenu(@ApiParam(value = "menus", required = true) @RequestParam(value = "menus", required = true) String menus,
//                 @ApiParam(value = "sys", required = true) @RequestParam(value = "sys", required = true) String sys,
//                 HttpServletRequest request, HttpServletResponse response) {
//        //1、创建root节点
//        MatrixMenu root = menuService.initAddRootMenu(sys);
//        //2、根据菜单数据创建节点
//        JSONArray array = JSONArray.parseArray(menus);
//        for (int i = 0; i < array.size(); i++) {
//            JSONObject object = (JSONObject) array.get(i);
//            service.initSaveMenu(object, root.getMenuId(), 1, sys);
//        }
//        List<String> chid = new ArrayList<>();
//        for (int i = 0; i < array.size(); i++) {
//            JSONObject object = (JSONObject) array.get(i);
//            service.initSaveChildIds(object);
//            chid.add(object.getString("id"));
//        }
//        //3、更新root的child
//        root.setMenuChilds(chid);
//        service.updateMenu(root);
//        return getRtn(REQUEST_SUCCESS, "");
//    }

//    @RequestMapping(value = "/move", method = RequestMethod.POST)
//    @ResponseStatus(HttpStatus.OK)
//    @ApiOperation(value = "上下移动menu节点")
//    public
//    @ResponseBody
//    Map moveMenu(@ApiParam(value = "menuId", required = true) @RequestParam(value = "menuId", required = true) String menuId,
//                 @ApiParam(value = "reqId", required = true) @RequestParam(value = "reqId", required = true) String reqId,
//                 @ApiParam(value = "移动类型  up 上移/down 下移", required = true) @RequestParam(value = "type", required = true) String type,
//                 @ApiParam(value = "wsUuid", required = false) @RequestParam(value = "wsUuid", required = false) String wsUuid,
//                 HttpServletRequest request, HttpServletResponse response) {
//        Map map = new HashMap();
//        try {
//            service.moveMenu(menuId, reqId, type,wsUuid);
//            map = getRtn(REQUEST_SUCCESS, "");
//        } catch (Exception e) {
//            logger.error("com.winit.menu.web.MenuController.moveMenu 异常", e);
//            map = getRtn(REQUEST_ERROR, "移动菜单异常." + e.getMessage());
//        }
//        return map;
//    }
    @RequestMapping(value = "/getMenu", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "获取menu")
//    @Cacheable(cacheNames = {"tree_menu"}, key = "#menuId  + '-' +  #menuSys")
    public
    @ResponseBody
    Map getMenu(@ApiParam(value = "req id", required = false) @RequestParam(value = "reqId", required = false) String reqId,
                @ApiParam(value = "menu id", required = false) @RequestParam(value = "menuId", required = false) String menuId,
                    @ApiParam(value = "menuSys menuSys", required = false) @RequestParam(value = "menuSys", defaultValue = "tom", required = false) String menuSys,
                    HttpServletRequest request, HttpServletResponse response) {
        MatrixMenu matrixMenu = this.matrixMenuService.getMenu(menuId, menuSys);
        return this.getRtn(BaseController.REQUEST_SUCCESS, "success", matrixMenu);
    }


    @RequestMapping(value = "/applyMenuUpdate", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "将menu change 推送至ws agent")
    public
    @ResponseBody
    Map applyMenuUpdate(@ApiParam(value = "req id", required = false) @RequestParam(value = "reqId", required = false) String reqId,
                @ApiParam(value = "menu id", required = false) @RequestParam(value = "menuId", required = false) String menuId,
                @ApiParam(value = "menuSys menuSys", required = false) @RequestParam(value = "menuSys", defaultValue = "tom", required = false) String menuSys,
                HttpServletRequest request, HttpServletResponse response) {
        ExecuteResult executeResult = this.matrixMenuService.applyMenuUpdate(menuId, reqId, menuSys);
        return this.getRtn(executeResult.getCode(), executeResult.getMsg(), null);
    }

    @RequestMapping(value = "/evictMenuTreeCache", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "清除menu_tree cache")
    @Caching(evict = {
            @CacheEvict(cacheNames = {"tree_menu"}, allEntries = true, condition = "#menuId == null and #menuSys == null"),
            @CacheEvict(cacheNames = {"feature_base_tree"}, allEntries = true),
            @CacheEvict(cacheNames = {"tree_menu"}, key = "#menuId  + '-' +  #menuSys")
    })
    public
    @ResponseBody
    Map evictMenuTreeCache(@ApiParam(value = "req id, 参数全为空时清除全部tree_menu cache", required = false) @RequestParam(value = "reqId", required = false) String reqId,
                @ApiParam(value = "menu id, 参数全为空时清除全部tree_menu cache", required = false) @RequestParam(value = "menuId", required = false) String menuId,
                @ApiParam(value = "menuSys , 参数全为空时清除全部tree_menu cache", required = false) @RequestParam(value = "menuSys", required = false) String menuSys,
                HttpServletRequest request, HttpServletResponse response) {
//        MatrixMenu matrixMenu = this.matrixMenuService.getMenu(menuId, menuSys);
        return this.getRtn(BaseController.REQUEST_SUCCESS, "success", null);
    }

    @RequestMapping(value = "/childSort", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "保存子节点顺序")
    @ResponseBody
    public Map saveChildSort(@ApiParam(value = "id", required = true) @RequestParam(value = "id", required = true) String id,
                             @ApiParam(value = "sort", required = true) @RequestParam(value = "sort", required = true) String sort) {
        matrixMenuService.saveChildSort(id,sort);
        return this.getRtn(REQUEST_SUCCESS, "");
    }
}
